import log from './log';

declare const window: Window & { LXAnalytics: Function };

function sendData(...args: any[]) {
  if (typeof window === 'object') {
    window.LXAnalytics && window.LXAnalytics.apply(window, [...args]);
  }
}

export function sendClickData(data: any, conf: any) {
  if (data) {
    if (conf.debug) log.info('click数据上报: ', data);
    const { valBid, text, valLab, options } = data;
    sendData('moduleClick', valBid || text, valLab, options);
  }
}

export function sendViewData(data: any, conf: any) {
  if (data) {
    if (conf.debug) log.info('view数据上报: ', data);
    const { valBid, text, valLab, options } = data;
    sendData('moduleView', valBid || text, valLab, options);
  }
}

export function sendPageViewData(pageViewData: any, conf: any) {
  const { data } = pageViewData;
  if (data) {
    if (conf.debug) log.info('PV数据上报: ', data);
    if (typeof data === 'string') {
      sendData('pageView', null, null, data);
    } else {
      const { cid, text, valLab, environment } = data;
      sendData('pageView', valLab, environment, cid || text);
    }
  }
}

function setMeta(name: string, val: string) {
  if (typeof window === 'object' && window.LXAnalytics) {
    // 优先使用API来设置meta，直接改DOM上的category上报不生效
    window.LXAnalytics('set', name, val);
  } else {
    const meta = document.head.querySelector(`meta[name="lx:${name}"]`);
    if (meta) {
      meta.setAttribute('content', val);
    } else {
      const metaEle = document.createElement('meta');
      metaEle.setAttribute('name', `lx:${name}`);
      metaEle.setAttribute('content', val);
      document.head.appendChild(metaEle);
    }
  }
}

export function onUrlChange(pageViewData: any, conf: any) {
  const { data } = pageViewData;
  if (data) {
    if (conf.debug) log.info('PV自动注入到meta标签: ', data);
    let pageCid;
    let pageCategory;
    let pageAppnm;
    if (typeof data === 'string') {
      pageCid = data;
    } else {
      const { cid, text, appnm, category } = data;
      pageCid = cid || text;
      pageCategory = category;
      pageAppnm = appnm;
    }
    if (pageCid) setMeta('cid', pageCid);
    if (pageCategory) setMeta('category', pageCategory);
    if (pageAppnm) setMeta('appnm', pageAppnm);
  }
}

export default {
  sendClickData,
  sendViewData,
  sendPageViewData,
  onUrlChange,
};
